import React, { useState, useRef } from 'react';
import CustomForm from 'src/components/CustomForm';
import { Input, message, Select, Radio } from 'antd';
import { MODEL_ENV } from 'src/utils/constant';
import services from 'src/services/api';
import BigFile from 'src/components/Upload/BigFile';

const RadioGroup = Radio.Group;
export default function Import(props) {
  const [type, setType] = useState(0);
  const [version, setVersion] = useState('');
  const [namelist, setNamelist] = useState([]);

  const form = useRef(null);

  const formItems = [
    {
      label: {
        label: '文件路径',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
        extra: ' 目前支持pmml模型类型，导入文件格式支持.pmml，文件大小限制为500M',
        // extra: ' 目前支持pmml/tensorflow serving模型类型，导入文件格式支持.pmml/.zip，文件大小限制为500M',
      },
      name: 'file_path',
      options: {
        initialValue: '',
        rules: [{ required: true, message: '请上传文件' }],
      },
      component: <BigFile action='/album' />,
    },
    {
      label: {
        label: '导入类型',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'type',
      options: {
        initialValue: type,
        rules: [{ required: true, message: '请选择导入类型' }],
      },
      component: (
        <RadioGroup onChange={(e) => setModelType(e.target.value)}>
          <Radio value={0}>新建模型</Radio>
          <Radio value={1}>添加已有版本</Radio>
        </RadioGroup>
      ),
    },
    type === 0
      ? {
          label: {
            label: '模型名称',
            className: 'tantuer-form-item tantuer-form-item-nowrap',
          },
          name: 'model_name',
          options: {
            initialValue: '',
            rules: [
              { required: true, message: '请填写模型服务名称' },
              { max: 128, message: '最长128个字符' },
              { pattern: /^[a-zA-Z][_a-zA-Z0-9]*$/, message: '限英文数字下划线，并以英文开头' },
            ],
          },
          component: <Input placeholder='请填写' style={{ width: '300px' }} />,
        }
      : false,
    type === 1
      ? {
          label: {
            label: '模型名称',
            className: 'tantuer-form-item tantuer-form-item-nowrap',
          },
          name: 'model_name',
          options: {
            initialValue: '',
            rules: [
              { required: true, message: '请填写模型服务名称' },
              { max: 128, message: '最长128个字符' },
              { pattern: /^[a-zA-Z][_a-zA-Z0-9]*$/, message: '限英文数字下划线，并以英文开头' },
            ],
          },
          component: (
            <Select
              style={{ width: '300px' }}
              onChange={(value) => {
                setCurVersion(value);
              }}
              allowClear
              showSearch
              showArrow={true}
              filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
              {namelist.map((it) => {
                return <Select.Option value={it.model_code}>{it.model_code}</Select.Option>;
              })}
            </Select>
          ),
          after: <Input value={version} disabled />,
        }
      : false,
    {
      label: {
        label: '运行环境',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
        // extra: 'pmml对应接口中服务类型为ai-serving，tfserving对应接口中服务类型为tf-serving',
        extra: 'pmml对应接口中服务类型为ai-serving',
      },
      name: 'runtime_env',
      options: {
        initialValue: '',
        rules: [{ required: true, message: '请选择运行环境' }],
      },
      component: (
        <Select style={{ width: '300px' }}>
          {MODEL_ENV.map((it,idx) => (
            <Select.Option value={it.value} key={idx}>{it.text}</Select.Option>
          ))}
        </Select>
      ),
    },
  ].filter(Boolean);

  function setCurVersion(value) {
    const cur = namelist.find((it) => it.model_code === value);
    if (cur) {
      let versions = cur.model_version;
      const ltg = cur.model_versions && cur.model_versions.length
      if (ltg) {
        versions = cur.model_versions[ltg - 1].model_version;
      };
      const nextNum = Number(versions.replace('v', '')) + 1;
      setVersion(`v${nextNum}`);
    }
  }

  function setModelType(value) {
    if (value === 1) {
      getNameList();
    }
    form.current.setFieldsValue({ model_name: '' });

    setType(value);
    setVersion('');
  }
  function getNameList() {
    services.repositoryModel.allList().then((res) => {
      if (res.code === 0) {
        const lists = res.data || [];
        setNamelist(lists);
      }
    });
  }

  function handleSubmit() {
    form.current.validateFields((err, values) => {
      if (!err) {
        const params = {
          model_name: values.model_name,
          model_version: type === 0 ? 'v1' : 'v' + (Number(version && version.replace("v","")) || 1),
          runtime_env: values.runtime_env,
          import_type: type,
          file_path: values.file_path.filePath,
        };

        services.repositoryModel.create(params).then((data) => {
          if (data.code === 0) {
            message.success(data.msg);
            if (props.closeModal) {
              props.closeModal();
            }
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  }

  return (
    <CustomForm
      closeModal={props.closeModal}
      createForm={(ref) => (form.current = ref)}
      formItems={formItems}
      colNum={1}
      onHandleSubmit={handleSubmit}
    />
  );
}
